package com.dongdongshop.controller;

import cn.hutool.json.JSONUtil;
import com.dongdongshop.data.Result;
import com.dongdongshop.domain.LoginUser;
import com.dongdongshop.dto.AdminDTO;
import com.dongdongshop.dto.SellerDTO;
import com.dongdongshop.enums.LoginTypeEnum;
import com.dongdongshop.shiro.DdUsernamePasswordToken;
import com.dongdongshop.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("login")
    public Result login(@RequestBody LoginUser loginUser) {
        Subject subject = SecurityUtils.getSubject();
        DdUsernamePasswordToken token = new DdUsernamePasswordToken(loginUser.getUsername(), loginUser.getPassword(), LoginTypeEnum.ADMIN);

        subject.login(token);

        AdminDTO adminDTO =(AdminDTO) SecurityUtils.getSubject().getPrincipal();
        LoginUser user =new LoginUser();
        user.setUsername(adminDTO.getUsername());
        user.setPassword(adminDTO.getPassword());
        user.setId(String.valueOf(adminDTO.getId()));
        String jwt = jwtUtil.createJwt(user.getId(), JSONUtil.toJsonStr(user), "admin");
        return Result.success(jwt);
    }

    @PostMapping("/seller/login")
    public Result sellerLogin(@RequestBody LoginUser loginUser) {
        Subject subject = SecurityUtils.getSubject();
        DdUsernamePasswordToken token = new DdUsernamePasswordToken(loginUser.getUsername(), loginUser.getPassword(), LoginTypeEnum.SELLER);

        subject.login(token);

        SellerDTO sellerDTO =(SellerDTO) SecurityUtils.getSubject().getPrincipal();
        LoginUser user =new LoginUser();
        user.setUsername(sellerDTO.getName());
        user.setPassword(sellerDTO.getPassword());
        user.setId(sellerDTO.getSellerId());
        String jwt = jwtUtil.createJwt(user.getId(), JSONUtil.toJsonStr(user), "seller");
        return Result.success(jwt);
    }
}
